package com.rjwh.dingdong.client.activity.loginregist;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.loginregist.fragment.AccountLoginFragment;
import com.rjwh.dingdong.client.activity.loginregist.fragment.MobileFastLoginFragment;
import com.rjwh.dingdong.client.bean.localbean.XiaomiAccountBeanData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.ThirdPartyLoginPresenter;
import com.rjwh.dingdong.client.mvp.view.ThirdPartyLoginView;
import com.rjwh.dingdong.client.thirdpartylogin.LoginApi;
import com.rjwh.dingdong.client.thirdpartylogin.OnLoginListener;
import com.rjwh.dingdong.client.thirdpartylogin.OnXiaomiLoginListener;
import com.rjwh.dingdong.client.thirdpartylogin.XiaomiLoginManager;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.widget.PagerSlidingTabStrip;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 登陆界面
 *
 * @author Kay
 * @ClassName ThirdPartyLoginActivity
 * @Description
 * @date 2016-10-9
 * @history 2016-10-9 author: description:
 */

public class ThirdPartyLoginActivity extends BaseActivity implements ThirdPartyLoginView {
    private static final int BIND_PHONE_NUM_REQUEST = 123;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.third_party_login_pagelidingtab)
    PagerSlidingTabStrip pagelidingtab;
    @BindView(R.id.third_party_login_viewpager)
    ViewPager viewpager;
    @BindView(R.id.third_party_login_xiaomi_btn)
    TextView thirdPartyLoginXiaomiBtn;

    private ArrayList<BaseFragment> listFragment = new ArrayList<>();

    private ThirdPartyLoginPresenter presenter;
    private String uid;
    private String nickname;
    private String avatar;
    private String apptype;
    private XiaomiLoginManager xiaomiLoginManager;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, ThirdPartyLoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.third_party_login_layout);
        ButterKnife.bind(this);
        initView();
        presenter = new ThirdPartyLoginPresenter(this, this);
    }

    private void initView() {
        initToolbarHelper();
        listFragment.add(AccountLoginFragment.getInstance());
        listFragment.add(MobileFastLoginFragment.getInstance());
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        viewpager.setAdapter(adapter);
        pagelidingtab.setViewPager(viewpager);
        initTabsValue();
        try {
            ApplicationInfo appInfo = this.getPackageManager()
                    .getApplicationInfo(getPackageName(),
                            PackageManager.GET_META_DATA);
            String msg = appInfo.metaData.getString("BaiduMobAd_CHANNEL");
            LogUtil.e("ThirdPartyLoginActivity", "msg: " + msg);
            if (!AsStrUtils.isEmpty(msg) && msg.equals("xiaomi")) {
                thirdPartyLoginXiaomiBtn.setVisibility(View.VISIBLE);
            } else {
                thirdPartyLoginXiaomiBtn.setVisibility(View.GONE);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * mPagerSlidingTabStrip默认值配置
     */
    private void initTabsValue() {

        // 底部游标颜色@color/blue_bg
        pagelidingtab.setIndicatorColor(getResources().getColor(R.color.blue_button_nor));
        pagelidingtab.setTabPaddingLeftRight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
        // tab的分割线颜色
        pagelidingtab.setDividerColor(Color.TRANSPARENT);
        // tab背景
        pagelidingtab.setBackgroundColor(getResources().getColor(R.color.white));
        // tab底线高度
        pagelidingtab.setUnderlineHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
        // 游标高度
        pagelidingtab.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
        // 选中的文字颜色
        pagelidingtab.setSelectedTextColor(getResources().getColor(R.color.blue_button_nor));
        // 正常文字颜色
        pagelidingtab.setTextColor(Color.BLACK);
        pagelidingtab.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
        pagelidingtab.setShouldExpand(true);

    }

    @Override
    public void showLoading() {
        showLoadDialog();
    }

    @Override
    public void dismissLoading() {
        dismissLoadDialog();
    }

    /**
     * 跳转到绑定手机号
     */
    @Override
    public void toBindMobileNumber() {
        Intent intent = new Intent(this, ThirdPartyLoginBindPhoneNumberActivity.class);
        intent.putExtra("uid", uid);
        intent.putExtra("nickname", nickname);
        intent.putExtra("avatar", avatar);
        intent.putExtra("apptype", apptype);
        startActivityForResult(intent, BIND_PHONE_NUM_REQUEST);
    }

    /**
     * 登录成功加载数据
     */
    @Override
    public void loadData() {
        RxBus.get().post(LocalConstant.RX__POST_LOGIN_UPDATE_UI, 1);
        RxBus.get().post(LocalConstant.RX__POST_WEB_FETCHINFO, 1);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BIND_PHONE_NUM_REQUEST && resultCode == RESULT_OK) {
            loadData();
        }
    }

    /* ***************FragmentPagerAdapter***************** */
    public class MyPagerAdapter extends FragmentPagerAdapter {

        private final String[] TITLES = {"帐号密码登录", "手机号快捷登录"};

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {
            return listFragment.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            // TODO Auto-generated method stub
            return super.isViewFromObject(view, object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            // super.destroyItem(container, position, object);
        }
    }

    private void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("登录");
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @OnClick({R.id.third_party_login_weixin_btn, R.id.third_party_login_qq_btn, R.id.third_party_login_weibo_btn, R.id.third_party_login_xiaomi_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.third_party_login_weixin_btn:

                LogUtil.e("ThirdPartyLoginActivity", "weixin_click");
                LoginApi aip = new LoginApi();
                aip.setPlatform(Wechat.NAME);
                aip.setOnLoginListener(new OnLoginListener() {

                    @Override
                    public boolean onLogin(String platform,
                                           HashMap<String, Object> res) {
                        LogUtil.e("ThirdPartyLoginActivity", "weixin onLogin");
                        Platform plat = ShareSDK.getPlatform(platform);
                        uid = plat.getDb().getUserId();
                        nickname = plat.getDb().getUserName();
                        avatar = plat.getDb().getUserIcon();
                        apptype = "weixin";
                        doLogin();
                        LogUtil.e("ThirdPartyLoginActivity", "／／name:　" + nickname + "//id: " + uid + "//icon: " + avatar);
                        return false;
                    }

                    @Override
                    public void onLoadingDailog() {
                        showLoading();
                    }

                    @Override
                    public void onDismissDailog() {
                        dismissLoading();
                    }
                });
                aip.login(this);
                break;
            case R.id.third_party_login_qq_btn:

                LoginApi aip1 = new LoginApi();
                aip1.setPlatform(QQ.NAME);
                aip1.setOnLoginListener(new OnLoginListener() {

                    @Override
                    public boolean onLogin(String platform,
                                           HashMap<String, Object> res) {
                        Platform plat = ShareSDK.getPlatform(platform);
                        uid = plat.getDb().getUserId();
                        nickname = plat.getDb().getUserName();
                        avatar = plat.getDb().getUserIcon();
                        apptype = "qq";
                        doLogin();
                        LogUtil.e("ThirdPartyLoginActivity", "／／name:　" + nickname + "//id: " + uid + "//icon: " + avatar);
                        return false;
                    }

                    @Override
                    public void onLoadingDailog() {
                        showLoading();
                    }

                    @Override
                    public void onDismissDailog() {
                        dismissLoading();
                    }
                });
                aip1.login(this);
                break;
            case R.id.third_party_login_weibo_btn:

                LoginApi aip2 = new LoginApi();
                aip2.setPlatform(SinaWeibo.NAME);
                aip2.setOnLoginListener(new OnLoginListener() {

                    @Override
                    public boolean onLogin(String platform,
                                           HashMap<String, Object> res) {
                        Platform plat = ShareSDK.getPlatform(platform);
                        uid = plat.getDb().getUserId();
                        nickname = plat.getDb().getUserName();
                        avatar = plat.getDb().getUserIcon();
                        apptype = "weibo";
                        doLogin();
                        LogUtil.e("ThirdPartyLoginActivity", "／／name:　" + nickname + "//id: " + uid + "//icon: " + avatar);
                        return false;
                    }

                    @Override
                    public void onLoadingDailog() {
                        showLoading();
                    }

                    @Override
                    public void onDismissDailog() {
                        dismissLoading();
                    }
                });
                aip2.login(this);
                break;
            case R.id.third_party_login_xiaomi_btn:
                //小米帐号登录
                xiaomiLoginManager = new XiaomiLoginManager(this);
                xiaomiLoginManager.setOnXiaomiLoginListener(new OnXiaomiLoginListener() {
                    @Override
                    public void onXiaomiLogin(XiaomiAccountBeanData data) {
                        if (data != null) {
                            uid = data.getUserId();
                            nickname = data.getMiliaoNick();
                            avatar = data.getMiliaoIcon();
                            apptype = "xiaomi";
                            doLogin();
                            LogUtil.e("ThirdPartyLoginActivity", "／／name:　" + nickname + "//id: " + uid + "//icon: " + avatar);
                        }
                    }

                    @Override
                    public void onLoadingDailog() {
                        showLoading();
                    }

                    @Override
                    public void onDismissDailog() {
                        dismissLoading();
                    }
                });
                xiaomiLoginManager.doLogin();
                break;
        }
    }

    private void doLogin() {
        presenter.doUserOuterSysLogin(uid, nickname, avatar, apptype);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        if (xiaomiLoginManager != null) {
            xiaomiLoginManager.onDestroy();
        }
    }
}
